<template>
  <el-dialog
    :title="title"
    :visible.sync="showDialog"
    width="60%"
    top="5%"
    :close-on-click-modal="isClickOutside"
    class="addTongBan"
    @close="cancel"
  >
    <div class="ruleBox">
      <el-form ref="form" :model="form" label-width="110px">
        <div v-for="(item, index) in form.eventCrossRules" :key="index">
          <h2 v-show="type === 'new'" style="padding-bottom: 16px">{{ '通办规则 ' + (index + 1) }}</h2>
          <el-form-item
            v-show="type !== 'show'"
            label="通办名称："
            :prop="'eventCrossRules.' + index + '.eventCrossRuleName'"
            :rules="{
              required: true,
              message: '通办名称不能为空',
              trigger: 'blur'
            }"
          >
            <el-input v-model="item.eventCrossRuleName" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item v-show="type === 'show'" label="通办名称：">
            {{ item.eventCrossRuleName }}
          </el-form-item>

          <div class="content">
            <div class="left">
              <h3>办理项</h3>
              <div class="box">
                <div class="line" v-for="(x, i) in item.handItem" :key="x.name + x.id">
                  <div class="line-label">
                    <img src="/img/itemManage/item.png" alt />
                    <span class="line-name">{{ x.name }}</span>
                  </div>
                  <i
                    class="line-icon el-icon-circle-close"
                    v-show="type !== 'show'"
                    @click="delItem(item, index, x, i)"
                  ></i>
                </div>
                <el-popover v-model="item.visible" placement="right" title="添加办理项" width="600" trigger="click">
                  <el-button v-show="type !== 'show'" slot="reference">+ 添加办理项</el-button>
                  <el-tree
                    ref="itemTree"
                    :data="eventTreeData"
                    class="popover-tree"
                    show-checkbox
                    node-key="id"
                    check-strictly
                    :default-expanded-keys="itemTree.defaultExpandedKeys"
                    :default-checked-keys="item.defaultCheckedKeys"
                    :props="itemTree.defaultProps"
                    @check-change="itemTreeCheckChange(item, index)"
                  ></el-tree>
                </el-popover>
              </div>
            </div>
            <div class="right">
              <h3>地区</h3>
              <div class="box">
                <div class="line" v-for="(x, i) in item.cities" :key="x.name + x.id">
                  <div class="line-label">
                    <img src="@/assets/img/place.png" alt />
                    <span class="line-name">{{ x.name }}</span>
                  </div>
                  <i
                    v-show="type !== 'show'"
                    class="line-icon el-icon-circle-close"
                    @click="delAreaItem(item, index, x, i)"
                  ></i>
                </div>
                <el-popover v-model="item.areaVisible" placement="right" title="添加地区" width="600" trigger="click">
                  <el-button v-show="type !== 'show'" slot="reference">+ 添加地区</el-button>
                  <el-tree
                    ref="areaTree"
                    :data="areaData"
                    class="popover-tree"
                    show-checkbox
                    node-key="key"
                    check-strictly
                    :default-expanded-keys="[areaData && areaData[0] && areaData[0].key]"
                    :default-checked-keys="item.defaultAreaCheckedKeys"
                    :props="areaTree.defaultProps"
                    @check-change="areaTreeCheckChange(item, index)"
                  ></el-tree>
                </el-popover>
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <el-button v-show="type === 'new'" type="primary" plain class="addNewRule" @click="addNewRule()">
        + 添加新规则
      </el-button>
    </div>
    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button @click="cancel">{{ type === 'show' ? '返 回' : '取 消' }}</el-button>
      <el-button v-show="type !== 'show'" type="primary" @click="submit()">
        {{ type === 'new' ? '确定添加' : '保存' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    getAreasTree,
    getImplementationTree,
    editEventcrossrule,
    batchEventcrossrule,
    getEventcrossrule
  } from '@/api/onethingCrossRule';
  export default {
    props: {
      areaCode: String,
      areaData: Array,
      eventTreeData: Array,
      eventTreeMap: Object,
      type: String,
      title: String,
      areaMap: Object,
      selectItem: Object
    },

    data() {
      return {
        showDialog: false,
        areaTreeData: [], //区域树
        itemTreeData: [], //事项
        itemTree: {
          defaultExpandedKeys: [],
          defaultProps: {
            disabled: 'children',
            children: 'children',
            label: 'name'
          }
        },
        areaTree: {
          defaultProps: {
            children: 'children',
            label: 'value'
          }
        },
        checkedCities: [],
        form: {
          eventCrossRules: [
            {
              eventCrossRuleName: '',
              areaVisible: false,
              cities: [],
              defaultAreaCheckedKeys: [],
              visible: false,
              handItem: [],
              defaultCheckedKeys: []
            }
          ]
        }
      };
    },
    computed: {
      isClickOutside() {
        return !(this.form.eventCrossRules.findIndex((e) => e.visible || e.areaVisible) > -1);
      }
    },
    watch: {
      showDialog(val) {
        if (val && this.type !== 'new') {
          this.getEventcrossrule();
        }
      }
    },
    methods: {
      initeData(item) {
        const { areaCodes, eventCrossRuleId, eventCrossRuleName, eventIds, state, stateDate, userId } = item;

        const cities =
          (areaCodes && areaCodes.map((e) => ({ name: this.areaMap[e]?.fullValue?.join('/'), id: e }))) || [];
        const handItem = (eventIds && eventIds.map((e) => ({ name: this.eventTreeMap[e]?.value, id: e }))) || [];
        this.form.eventCrossRules = [
          {
            state,
            stateDate,
            eventCrossRuleId,
            userId,
            eventCrossRuleName,
            areaVisible: false,
            cities: cities,
            defaultAreaCheckedKeys: areaCodes,
            visible: false,
            handItem: handItem,
            defaultCheckedKeys: eventIds
          }
        ];
      },
      async getEventcrossrule() {
        const { data } = await getEventcrossrule(this.selectItem.eventCrossRuleId);
        if (data.code === 200) {
          this.initeData(data.result);
        }
      },
      delItem(item, index, x, i) {
        item.handItem.splice(i, 1);
        let tempIndex = item.defaultCheckedKeys.findIndex((e) => e === x.id);
        if (tempIndex > -1) {
          item.defaultCheckedKeys.splice(tempIndex, 1);

          this.$refs['itemTree'][index].setCheckedKeys(item.defaultCheckedKeys);
        }
      },

      itemTreeCheckChange(item, index) {
        const checkeds = this.$refs['itemTree'][index].getCheckedNodes();
        const keys = this.$refs['itemTree'][index].getCheckedKeys();
        item.defaultCheckedKeys = keys;
        item.handItem = checkeds.map((e) => ({ name: e.name, id: e.id }));
      },
      delAreaItem(item, index, x, i) {
        item.cities.splice(i, 1);
        let tempIndex = item.defaultAreaCheckedKeys.findIndex((e) => e === x.id);
        if (tempIndex > -1) {
          item.defaultAreaCheckedKeys.splice(tempIndex, 1);

          this.$refs['areaTree'][index].setCheckedKeys(item.defaultAreaCheckedKeys);
        }
      },
      areaTreeCheckChange(item, index) {
        const checkeds = this.$refs['areaTree'][index].getCheckedNodes();
        const keys = this.$refs['areaTree'][index].getCheckedKeys();
        item.defaultAreaCheckedKeys = keys;
        item.cities = checkeds.map((e) => ({ name: this.areaMap[e.key]?.fullValue?.join('/'), id: e.key }));
      },
      async getAreasTree() {
        const { data } = await getAreasTree({ parentId: this.areaCode });
        if (data.code === 200) {
          this.areaTree.data = [data.result];
        }
      },
      async getImplementationTree() {
        const { data } = await getImplementationTree();
        if (data.code === 200) {
          this.itemTree.data = data.result;
        }
      },
      async submit() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            const tempList = [];
            let localValid = true;
            this.form.eventCrossRules.forEach((item, index) => {
              if (item.defaultCheckedKeys.length === 0) {
                localValid = false;
                this.$message.error(`通办规则 ${index + 1} 的办理项不能为空！`);
              }
              if (item.defaultAreaCheckedKeys.length === 0) {
                localValid = false;
                this.$message.error(`通办规则 ${index + 1} 的地区不能为空！`);
              }
              tempList.push({
                areaCode: this.areaCode,
                areaCodes: item.defaultAreaCheckedKeys,
                eventCrossRuleId: item.eventCrossRuleId,
                eventCrossRuleName: item.eventCrossRuleName,
                eventIds: item.defaultCheckedKeys
              });
            });
            if (!localValid) return;
            let result;
            if (this.type === 'new') {
              const { data } = await batchEventcrossrule(tempList);
              result = data;
            } else {
              const { data } = await editEventcrossrule(tempList[0]);
              result = data;
            }
            if (result.success) {
              this.$message.success(`${this.type === 'new' ? '新建' : '编辑'}通办成功！`);
              this.$emit('updateList');
              this.cancel();
            }
          } else {
            this.$message.error('表单验证有误！');
          }
        });
      },
      addNewRule() {
        this.form.eventCrossRules.push({
          areaVisible: false,
          cities: [],
          defaultAreaCheckedKeys: [],
          visible: false,
          handItem: [],
          defaultCheckedKeys: []
        });
      },
      cancel() {
        this.showDialog = false;
        this.form.eventCrossRules = [
          {
            eventCrossRuleName: '',
            areaVisible: false,
            cities: [],
            defaultAreaCheckedKeys: [],
            visible: false,
            handItem: [],
            defaultCheckedKeys: []
          }
        ];
        //清空树的选择
        // this.$refs['itemTree'][index].setCheckedKeys(item.defaultCheckedKeys)
        const itemTreeRefs = this.$refs['itemTree'];
        if (itemTreeRefs && itemTreeRefs.length) {
          itemTreeRefs.forEach((item) => {
            item.setCheckedKeys([]);
          });
        }
        const areaTreeRefs = this.$refs['areaTree'];
        if (areaTreeRefs && areaTreeRefs.length) {
          areaTreeRefs.forEach((item) => {
            item.setCheckedKeys([]);
          });
        }
      }
    }
  };
</script>

<style lang="scss">
  .popover-tree {
    max-height: 600px;
    overflow-x: hidden;
    overflow-y: auto;
    .el-checkbox__input.is-disabled .el-checkbox__inner {
      display: none;
    }
  }
  .addTongBan {
    .ruleBox {
      max-height: 600px;
      overflow-x: hidden;
      overflow-y: auto;
    }
    h2 {
      font-size: 16px;
      font-weight: bold;
    }
    .addNewRule {
      margin-left: 30px;
    }
    .content {
      display: flex;
      margin: 10px 0;
      padding: 0 30px;
      .left,
      .right {
        flex: 1;
        width: 0;
        margin-right: 10px;
        position: relative;
      }
      .left img {
        width: 30px;
        height: 30px;
        margin-right: 10px;
      }
      .right img {
        width: 16px;
        height: 16px;
        margin-right: 10px;
      }
      h3 {
        font-size: 14px;
        font-weight: bold;
      }
      .box {
        padding: 20px;
        border: 1px solid #409eff;
        border-radius: 5px;
        margin-top: 10px;
        height: 200px;
        width: calc(100% - 40px);
        overflow: auto;
        .line {
          display: flex;
          margin-bottom: 10px;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
          .line-label {
            display: flex;
            align-items: center;
            width: calc(100% - 30px);
          }
          .line-name {
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            width: calc(100% - 20px);
            display: inline-block;
          }
          .line-icon {
            cursor: pointer;
            color: red;
          }
        }
      }
    }
  }
</style>
